﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OptionParameterExtensions.cs" company="Matthias Friedrich">
//   Copyright © Matthias Friedrich 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace CommandlineHandling
{
    using System;
    using System.ComponentModel;

    public static class OptionParameterExtensions
    {
        public static T GetValue<T>(this OptionParameter p)
        {
            if (p == null)
            {
                return default(T);
            }

            if (string.IsNullOrEmpty(p.Value))
            {
                return default(T);
            }

            return p.Value.Convert<T>();
        }

        public static object GetValue(this OptionParameter p, Type t)
        {
            if (p == null)
            {
                return null;
            }

            if (string.IsNullOrEmpty(p.Value))
            {
                return null;
            }

            TypeConverter converter = TypeDescriptor.GetConverter(t);
            if (converter.CanConvertFrom(typeof(string)))
            {
                return converter.ConvertFrom(p.Value);
            }

            return null;
        }
    }
}